package com.bookcode.service.impl;
import com.bookcode.dao.DemoInfoRepository;
import com.bookcode.entity.DemoInfo;
import com.bookcode.service.DemoInfoService;
import javassist.NotFoundException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Optional;
@Service
public class DemoInfoServiceImpl implements DemoInfoService {
    //这里的单引号不能少，否则会报错，被识别是一个对象;
    public static final String CACHE_KEY = "'demoInfo'";
    @Resource
    private DemoInfoRepository demoInfoRepository;
    public static final String DEMO_CACHE_NAME = "demo";
    @CacheEvict(value=DEMO_CACHE_NAME,key=CACHE_KEY)
    @Override
    public DemoInfo save(DemoInfo demoInfo){
        return demoInfoRepository.save(demoInfo);
    }
    @Cacheable(value=DEMO_CACHE_NAME,key="'demoInfo_'+#id")
    @Override
    public Optional<DemoInfo> findById(Long id){
        System.err.println("没有走缓存！"+id);
        return demoInfoRepository.findById(id);
    }
    @CachePut(value = DEMO_CACHE_NAME,key = "'demoInfo_'+#updated.getId()")
    @Override
    public DemoInfo update(DemoInfo updated) throws NotFoundException {
        Optional<DemoInfo>  opdemoInfo = demoInfoRepository.findById(updated.getId());
        if(opdemoInfo == null){
            throw new NotFoundException("No find");
        }
        DemoInfo demoInfo;
        opdemoInfo.get().setName(updated.getName());
        opdemoInfo.get().setPwd(updated.getPwd());
        demoInfo=opdemoInfo.get();
        return demoInfo;
    }
    @CacheEvict(value = DEMO_CACHE_NAME,key = "'demoInfo_'+#id")
    @Override
    public void delete(Long id) {
        System.out.println("模拟删除："+id);
    }
}
